package com.xwdeshj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xwdeshj.dal.Dal_XwUserinfo;
import com.xwdeshj.entity.*;
import com.xwdeshj.repository.*;
import com.xwdeshj.result.IMoocJSONResult;
import com.xwdeshj.service.XwBusinessInfoService;
import com.xwdeshj.service.XwUserinfoService;
import com.xwdeshj.utils.DateUtil;
import com.xwdeshj.utils.helper;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by BKWJA on 2018/11/19.
 */
@Service("xwUserinfoService")
@Slf4j
public class XwUserinfoServiceImpl implements XwUserinfoService {

    @Autowired
    private XwUserinfoRepository xwUserinfoRepository;
    @Autowired
    private Sid sid;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private XwBusinessInfoRepository xwBusinessInfoRepository;
    @Autowired
    private XwFarmBasicinfoRepository xwFarmBasicinfoRepository;
    @Autowired
    private XwScenicBasicinfoRepository xwScenicBasicinfoRepository;
    @Autowired
    private XwFarmRoominfoRepository xwFarmRoominfoRepository;
    @Autowired
    private XwFarmCollectinfoRepository xwFarmCollectinfoRepository;
    @Autowired
    private XwFarmAtlasinfoRepository xwFarmAtlasinfoRepository;
    @Autowired
    private XwFarmFoodinfoRepository xwFarmFoodinfoRepository;
    @Autowired
    private XwFarmDiscussinfoRepository xwFarmDiscussinfoRepository;

    @Autowired
    private XwSceincCollectinfoReository xwSceincCollectinfoReository;
    @Autowired
    private XwSceincDiscussinfoReopsitory xwSceincDiscussinfoReopsitory;
    @Autowired
    private XwSceincEntertainmentRepository xwSceincEntertainmentRepository;
    @Autowired
    private XwScenicAtlasinfoRepository xwScenicAtlasinfoRepository;
    @Autowired
    private XwCustomShopRepository xwCustomShopRepository;

    Dal_XwUserinfo dal_xwUserinfo = new Dal_XwUserinfo();

    /**
     * 登录
     */
    @Override
    public IMoocJSONResult login(String username, String password, HttpServletResponse response) {

        IMoocJSONResult result = new IMoocJSONResult();
        String tel = username;
        XwUserinfo xwUserinfo = new XwUserinfo();
        xwUserinfo.setUserName(username);
        boolean falg = xwUserinfoRepository.exists(Example.of(xwUserinfo));
        if (falg) {
            XwUserinfo user = xwUserinfoRepository.findByUserNameOrUserTel(username, tel);
            if (user != null) {
                //将密码转为MD5格式
                String md5Pwd = DigestUtils.md5DigestAsHex(password.getBytes());
                String userRole = user.getUserRole();
                if (md5Pwd.equals(user.getUserPassword())) {
                    //除了普通用户之前，所有角色均有权登录该系统
                    if (!"0".equals(userRole)) {
                        //将用户加密id存入cookie中
                        Cookie hc1 = new Cookie("uid", String.valueOf(user.getUserId()));
                        hc1.setPath("/");
                        hc1.setMaxAge(60 * 60 * 24);
                        response.addCookie(hc1);

                        //将用户加密id存入cookie中
                        Cookie hc2 = new Cookie("uid_encryptid", user.getUserEncryptid());
                        hc2.setPath("/");
                        hc2.setMaxAge(60 * 60 * 24);
                        response.addCookie(hc2);

                        //将登录者的角色（部门号）存入cookie中
                        Cookie hc3 = new Cookie("admin_role", user.getUserRole());
                        hc3.setPath("/");
                        hc3.setMaxAge(60 * 60 * 24);
                        response.addCookie(hc3);

                        result.setStatus(0);
                        result.setMsg("登录成功");
                        result.setData(user);
                    } else {
                        result.setStatus(40003);
                        result.setMsg("该用户无权登录该系统，请联系管理员！");
                        result.setData("");
                    }
                } else {
                    result.setStatus(500);
                    result.setMsg("登录失败，请检查用户名和密码是否正确");
                    result.setData("");
                }
            } else {
                result.setStatus(40002);
                result.setMsg("该用户不存在！");
                result.setData("");
            }
        } else {
            result.setStatus(40002);
            result.setMsg("该用户不存在！");
            result.setData("");
        }
        System.out.println("login:" + result);
        return result;
    }

    /**
     * 强制修改密码
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject forceModifyPassword(String userEncryptid, String oldPwd, String newPwd) {

        JSONObject result = new JSONObject();
        XwUserinfo xwUserinfo = new XwUserinfo();
        xwUserinfo.setUserEncryptid(userEncryptid);
        boolean falg = xwUserinfoRepository.exists(Example.of(xwUserinfo));
        if (falg) {
            XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(userEncryptid);
            String oldPwdMD5 = DigestUtils.md5DigestAsHex(oldPwd.getBytes()); //加密
            if (userinfo != null) {
                if (oldPwdMD5.equals(userinfo.getUserPassword())) {
                    userinfo.setUserPassword(DigestUtils.md5DigestAsHex(newPwd.getBytes()));
                    userinfo.setUserFirst("1");
                    userinfo.setUserUpdatetime(new Date());
                    xwUserinfoRepository.save(userinfo);
                    result.put("status", 0);
                    result.put("msg", "密码更换成功，请重新登录!");
                } else {
                    result.put("status", 40002);
                    result.put("msg", "原始密码错误!");
                }
            } else {
                result.put("status", 500);
                result.put("msg", "该用户不存在!");
            }
        } else {
            result.put("status", 500);
            result.put("msg", "该用户不存在!");
        }
        System.out.println("forceModifyPassword:" + result.toString());
        return result;
    }

    /**
     * 添加用户，注册用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public IMoocJSONResult addsave(String username, String userTel, String userRealname,
                                   String userAvatar, String userSex, String user_role,
                                   String password, String email,HttpServletRequest request) {
        IMoocJSONResult result = new IMoocJSONResult();

        String uid_encryptid = helper.ReadCookieMap(request, "uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request, "uid").toString();
        if (!"".equals(uid) && !"".equals(uid_encryptid)) {
            XwUserinfo userinfo = new XwUserinfo();
            try {
                XwUserinfo user = xwUserinfoRepository.findByUserNameOrUserTel(username, userTel);
                if (user == null) {
                    userinfo.setUserFirst("0"); //首次登录
                    userinfo.setUserEncryptid(sid.nextShort()); //加密id
                    userinfo.setUserName(username); //用户名
                    userinfo.setUserTel(userTel); //电话
                    userinfo.setUserRealname(userRealname); //姓名
                    userinfo.setUserAvatar(userAvatar); //头像
                    userinfo.setUserSex(userSex); //性别
                    userinfo.setUserMail(email);//邮箱
                    if (user_role == null || "".equals(user_role)) {
                        userinfo.setUserRole("0"); //用户
                    } else {
                        userinfo.setUserRole(user_role); //角色
                    }
                    userinfo.setUserPassword(DigestUtils.md5DigestAsHex(password.getBytes())); //密码
                    userinfo.setJurisdiction(""); //启用
                    userinfo.setUserCreatetime(new Date());
                    userinfo.setUserUpdatetime(new Date());
                    xwUserinfoRepository.save(userinfo);
                    result.setStatus(0);
                    result.setMsg("ok");
                    result.setData("");
                } else {
                    result.setStatus(500);
                    result.setMsg("该用户已存在!");
                    result.setData("");
                }

            } catch (Exception e) {
                e.printStackTrace();
                result.setStatus(500);
                result.setMsg(String.valueOf(e));
                result.setData("");
            }
        }else {
            result.setStatus(5000);
            result.setMsg("uid不能为空,请先登录！");
        }
        System.out.println("addsave:"+result.toString());
        return result;
    }

    /**
     * 查询用户信息列表
     */
    @Override
    public JSONObject querUserList(Integer pagesize, Integer pageindex, String starttime,
                                   String endtime, String searchval, String searchkey,
                                   String sortfild, String sortway, String user_role) {
        JSONObject result = new JSONObject();

        String sql = "SELECT\n" +
                "  a.user_encryptId,\n" +
                "  a.user_name,\n" +
                "  a.user_tel,\n" +
                "  a.user_realName,\n" +
                "  a.user_Avatar,\n" +
                "  a.user_sex,\n" +
                "  a.user_hobby_zt,\n" +
                "  a.user_hobby_yw,\n" +
                "  a.user_role,\n" +
                "  a.user_mail,\n" +
                "  a.user_createtime,\n" +
                "  b.business_encryptId,\n" +
                "  b.farm_encryptId,\n" +
                "  b.sec_encryptId, \n" +
                "  b.business_type AS businessTypeid\n" +
                "\n" +
                "FROM xw_userinfo a\n" +
                "  LEFT JOIN xw_business_info b ON a.user_encryptId = b.business_encryptId ";

        StringBuffer sb = new StringBuffer();
        sb.append(" 1=1 ");
        //时间查询
        if (!starttime.equals("")) {
            starttime += " 00.00.01";
            endtime += " 23.59.59";
            sb.append(" and a.user_createtime >= '" + starttime + "' and a.user_createtime <= '" + endtime + "' ");
        }
        //搜索内容查询
        if (!searchval.equals("")) {
            sb.append(" and ( a." + searchkey + " like '%" + searchval + "%' )");
        }
        //角色查询
        if (!user_role.equals("")) {
            sb.append(" and ( a.user_role=" + user_role + " )");
        }
        //排序
        if (!sortfild.equals("")) {
            sb.append(" order by a." + sortfild + " " + sortway + " ");
        }
        try {
            sql = sql + " where " + sb.toString() + " limit " + (pageindex - 1) * pagesize + "," + pagesize;
            //分页SQL
            String sql2 = "SELECT\n" +
                    " count(*)\n" +
                    "FROM xw_userinfo a\n" +
                    "  LEFT JOIN xw_business_info b ON a.user_encryptId = b.business_encryptId " +
                    " where " + sb.toString();

            SqlRowSet rs = jdbcTemplate.queryForRowSet(sql);
            SqlRowSet rs2 = jdbcTemplate.queryForRowSet(sql2);
            result.put("status", 0);
            result.put("msg", "ok");
            while (rs2.next()) {
                Integer count = rs2.getInt(1);
                result.put("recordcount", count);
                if (count % pagesize == 0) {
                    result.put("pagecount", count / pagesize);
                } else {
                    result.put("pagecount", count / pagesize + 1);
                }
            }
            JSONArray jsonArray = new JSONArray();
            while (rs.next()) {
                JSONObject object = new JSONObject();
                object.put("user_encryptId", rs.getString("user_encryptId"));
                object.put("user_name", rs.getString("user_name") == null ? "" : rs.getString("user_name"));
                object.put("user_tel", rs.getString("user_tel") == null ? "" : rs.getString("user_tel"));
                object.put("user_realName", rs.getString("user_realName") == null ? "" : rs.getString("user_realName"));
                object.put("user_Avatar", rs.getString("user_Avatar") == null ? "" : rs.getString("user_Avatar"));
                object.put("user_sex", rs.getString("user_sex") == null ? "" : rs.getString("user_sex"));
                object.put("user_hobby_zt", rs.getString("user_hobby_zt") == null ? "" : rs.getString("user_hobby_zt"));
                object.put("user_hobby_yw", rs.getString("user_hobby_yw") == null ? "" : rs.getString("user_hobby_yw"));
                object.put("user_role", rs.getString("user_role") == null ? "" : rs.getString("user_role"));
                object.put("user_mail", rs.getString("user_mail") == null ? "" : rs.getString("user_mail"));
                object.put("user_createtime", DateUtil.DateToString(rs.getDate("user_createtime")));
                object.put("business_encryptId", rs.getString("business_encryptId") == null ? "" : rs.getString("business_encryptId"));
                object.put("farm_encryptId", rs.getString("farm_encryptId") == null ? "" : rs.getString("farm_encryptId"));
                object.put("sec_encryptId", rs.getString("sec_encryptId") == null ? "" : rs.getString("sec_encryptId"));
                object.put("businessTypeid", rs.getString("businessTypeid") == null ? "" : rs.getString("businessTypeid"));
                jsonArray.add(object);
            }
            result.put("list", jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("status", 500);
            result.put("msg", e);
        }
        System.out.println("querUserList:" + result.toString());
        return result;
    }


    /**
     * 获取用户基本信息（一条）
     */
    @Override
    public IMoocJSONResult userInformation(String user_encryptId,HttpServletRequest request) {
        IMoocJSONResult result = new IMoocJSONResult();
        String uid_encryptid = helper.ReadCookieMap(request, "uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request, "uid").toString();
        if (!"".equals(uid) && !"".equals(uid_encryptid)) {
            if (!"".equals(user_encryptId)) {
                try {
                    //检查对象是否存在
                    XwUserinfo userinfo = new XwUserinfo();
                    userinfo.setUserEncryptid(user_encryptId);
                    boolean temp = xwUserinfoRepository.exists(Example.of(userinfo));
                    if (temp) {
                        XwUserinfo user = xwUserinfoRepository.findByUserEncryptid(user_encryptId);
                        if (user != null) {
                            result.setStatus(0);
                            result.setMsg("ok");
                            result.setData(user);
                        } else {
                            result.setStatus(500);
                            result.setMsg("该用户不存在！");
                            result.setData("");
                        }
                    } else {
                        result.setStatus(500);
                        result.setMsg("该用户不存在！");
                        result.setData("");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    result.setStatus(500);
                    result.setMsg(String.valueOf(e));
                    result.setData("");
                }
            } else {
                result.setStatus(500);
                result.setMsg("user_encryptId不能为空！");
                result.setData("");
            }
        }else {
            result.setStatus(4001);
            result.setMsg("uid不能为空,请先登录！");
            result.setData("");
        }

        return result;
    }


    //修改用户信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject updateInformation(String user_encryptId, String user_realName, String user_role,
                                        String user_tel, String user_mail, String user_Avatar,
                                        String user_password, String user_sex, String farm_encryptId,
                                        String sec_encryptId,
                                        HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request, "uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request, "uid").toString();
        if (!"".equals(uid) && !"".equals(uid_encryptid)) {
            if (!"".equals(user_encryptId)) {
                XwUserinfo xwUserinfo = new XwUserinfo();
                xwUserinfo.setUserEncryptid(user_encryptId);
                boolean temp = xwUserinfoRepository.exists(Example.of(xwUserinfo));
                if (temp) {
                    XwUserinfo user = xwUserinfoRepository.findByUserEncryptid(user_encryptId);

                    if(!user_role.equals(user.getUserRole()) && ("1").equals(user_role)){
                        //如果是直接修改为商家
                        result.put("status", 40002);
                        result.put("msg", "该用户之前不是商家，无法直接升级为商家，" +
                                "请注册为本站的普通用户后在进行商家升级！");
                        return result;
                    }

                    if (user.getUserRole().equals("1")) {
                        //删除商家，之前存在的所有信息
                        delbusinessinfo(user_encryptId, farm_encryptId, sec_encryptId, request);
                    }
                    if (!"".equals(user_realName) && user_realName != null) {
                        user.setUserRealname(user_realName);
                    }
                    if (!"".equals(user_role) && user_role != null) {
                        user.setUserRole(user_role);
                    }
                    if (!"".equals(user_tel) && user_tel != null) {

                        //第一步 ：应查询该电话号码是否 已经存在（1、用户信息表）
                        List<XwUserinfo> userTellist = xwUserinfoRepository.findByUserTel(user_tel);
                        if(userTellist.size() == 0){
                            //不存在
                            user.setUserTel(user_tel);

                            if("1".equals(user.getUserRole())){
                                //如果是商家
                                XwBusinessInfo xwBusinessInfo = new XwBusinessInfo();
                                xwBusinessInfo.setBusinessEncryptid(user_encryptId);
                                boolean Teltemp = xwBusinessInfoRepository.exists(Example.of(xwBusinessInfo));
                                if(Teltemp){
                                    XwBusinessInfo businessInfo = xwBusinessInfoRepository.findByBusinessEncryptid(user_encryptId);
                                    businessInfo.setBusinessTel(user_tel.trim());
                                    xwBusinessInfoRepository.save(businessInfo);
                                }
                            }
                        }


                    }
                    if (!"".equals(user_mail) && user_mail != null) {
                        user.setUserMail(user_mail);
                    }
                    if (!"".equals(user_Avatar) && user_Avatar != null) {
                        user.setUserAvatar(user_Avatar);
                    }
                    if (!"".equals(user_password) && user_password != null) {
                        //默认密码
                        if (!user_password.equals("xwdeshj@2018")) {
                            user.setUserPassword(DigestUtils.md5DigestAsHex(user_password.getBytes()));
                        }
                    }
                    if (!"".equals(user_sex) && user_sex != null) {
                        user.setUserSex(user_sex);
                    }
                    if (user != null) {
                        try {
                            user.setUserUpdatetime(new Date());
                            xwUserinfoRepository.save(user);
                            result.put("status", 0);
                            result.put("msg", "ok");
                        } catch (Exception e) {
                            e.printStackTrace();
                            result.put("status", 5000);
                            result.put("msg", e);
                        }
                    }
                } else {
                    result.put("status", 40002);
                    result.put("msg", "该用户不存在！");
                }

            } else {
                result.put("status", 5000);
                result.put("msg", "user_encryptId不能为空！");
            }
        } else {
            result.put("status", 40001);
            result.put("msg", "uid不能为空,请先登录！");
        }
        System.out.println("updateInformation:" + result.toString());
        return result;
    }


    /**
     * 删除用户信息，如果是商家，同时删除商家的所有信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject delInformation(String user_encryptId,String farm_encryptId,String sec_encryptId,
                                     HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request, "uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request, "uid").toString();
        if(!"".equals(uid) && !"".equals(uid_encryptid)){
            if (!"".equals(user_encryptId) && user_encryptId != null) {
                try {
                    if (user_encryptId.indexOf(",") == -1) {
                        XwUserinfo xwUserinfo = new XwUserinfo();
                        xwUserinfo.setUserEncryptid(user_encryptId);
                        boolean temp = xwUserinfoRepository.exists(Example.of(xwUserinfo));
                        if(temp){
                           XwBusinessInfo xwBusinessInfo = new XwBusinessInfo();
                           xwBusinessInfo.setBusinessEncryptid(user_encryptId);
                           boolean businesstmep = xwBusinessInfoRepository.exists(Example.of(xwBusinessInfo));
                           if(businesstmep){
                               //查看是否有商家记录，若有就删除商家，之前存在的所有信息
                               delbusinessinfo(user_encryptId, farm_encryptId, sec_encryptId, request);
                           }

                            //单个删除
                            int flag = xwUserinfoRepository.deleteByUserEncryptid(user_encryptId);
                            if (flag == 1) {
                                result.put("status", 0);
                                result.put("msg", "ok");
                            } else {
                                result.put("status", 500);
                                result.put("msg", "删除失败！");
                            }
                        }

                    } else {
                        //批量删除，功能暂时屏蔽，无法同时删除多个商家所有信息
                        int flag = 0;
                        String[] tids = user_encryptId.split(",");
                        for (int i = 0; i < tids.length; i++) {
                            flag = xwUserinfoRepository.deleteByUserEncryptid(tids[i]);
                        }
                        if (flag == 1) {
                            result.put("status", 0);
                            result.put("msg", "ok");
                        } else {
                            result.put("status", 500);
                            result.put("msg", "删除失败！");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    result.put("status", 500);
                    result.put("msg", e);
                }
            } else {
                result.put("status", 500);
                result.put("msg", "user_encryptId不能为空！");
            }
        }else {
            result.put("status", 40002);
            result.put("msg", "uid不能为空,请先登录！");
        }

        System.out.println("delInformation：" + result.toString());
        return result;
    }

    /**
     * 用户名搜索，验证用户名是否存在
     */
    @Override
    public JSONObject userquery(String field, String value, HttpServletRequest request, HttpServletResponse response) {

        JSONObject result = new JSONObject();
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("UTF-8");

            //用户名搜索
            String sql = "SELECT\n" +
                    "  user_id,\n" +
                    "  user_encryptId,\n" +
                    "  user_name as username,\n" +
                    "  user_tel,\n" +
                    "  user_realName,\n" +
                    "  user_role,\n" +
                    "  user_mail\n" +
                    "FROM xw_userinfo\n" +
                    "WHERE user_role != '2' ";
            StringBuffer sb = new StringBuffer();
            if (field.equals("username") && !field.equals("")) {
                field = "user_realName";
                sb.append(" and " + field + " IN ('" + value + "') ");

            } else if (field.equals("tel") && !field.equals("")) {
                //电话号码搜索
                field = "user_tel";
                sb.append(" and " + field + " IN ('" + value + "') ");
            }

            sql = sql + sb.toString();
            SqlRowSet rs = jdbcTemplate.queryForRowSet(sql);
            JSONArray jsonArray = new JSONArray();
            while (rs.next()) {
                JSONObject object = new JSONObject();
                object.put("user_id", rs.getString("user_id"));
                object.put("user_encryptId", rs.getString("user_encryptId"));
                object.put("user_tel", rs.getString("user_tel") == null ? "" : rs.getString("user_tel"));
                object.put("user_realName", rs.getString("user_realName") == null ? "" : rs.getString("user_realName"));
                object.put("user_role", rs.getString("user_role") == null ? "" : rs.getString("user_role"));
                object.put("mail", rs.getString("user_mail") == null ? "" : rs.getString("user_mail"));
                jsonArray.add(object);
            }
            result.put("list", jsonArray);
            result.put("status", 0);
            result.put("msg", "ok");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("status", 500);
            result.put("msg", e);
        }
        System.out.println("userquery:" + result.toString());
        return result;
    }


    /**
     * 删除商家基本信息,用于解决jpa方法的先后顺序
     * 方法
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject delbusinessinfo(String business_encryptId, String farm_encryptId, String sec_encryptId,
                                      HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid = helper.ReadCookieMap(request,"uid").toString();//读取当前操作人用户id
        String u_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();//读取当前操作人用户加密id
        if((!"".equals(uid) && uid != null) && (!"".equals(u_encryptid) && u_encryptid != null)){
            if (!"".equals(business_encryptId) && business_encryptId != null) {
                try {
                    if (business_encryptId.indexOf(",") == -1) {

                        XwBusinessInfo businessInfo = new XwBusinessInfo();
                        businessInfo.setBusinessEncryptid(business_encryptId);
                        boolean temp = xwBusinessInfoRepository.exists(Example.of(businessInfo));

                        if (temp) {
                            //存在
                            if (!"0".equals(farm_encryptId) && !"".equals(farm_encryptId)) {
                                //删除农家乐商家信息，单个删除

                                //农家乐图集
                                XwFarmAtlasinfo xwFarmAtlasinfo = new XwFarmAtlasinfo();
                                xwFarmAtlasinfo.setFarmEncryptid(farm_encryptId);
                                xwFarmAtlasinfo.setBusinessEncryptid(business_encryptId);
                                boolean atlastemp = xwFarmAtlasinfoRepository.exists(Example.of(xwFarmAtlasinfo));
                                if(atlastemp){
                                    //查询到有相关记录
                                    xwFarmAtlasinfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //农家乐收藏信息
                                XwFarmCollectinfo xwFarmCollectinfo = new XwFarmCollectinfo();
                                xwFarmCollectinfo.setBusinessEncryptid(business_encryptId);
                                xwFarmCollectinfo.setFarmtypeEncryptid(farm_encryptId);
                                boolean colltemp = xwFarmCollectinfoRepository.exists(Example.of(xwFarmCollectinfo));
                                if (colltemp){
                                    //查询到有相关记录
                                    xwFarmCollectinfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //农家乐评论信息
                                XwFarmDiscussinfo xwFarmDiscussinfo = new XwFarmDiscussinfo();
                                xwFarmDiscussinfo.setBusinessEncryptid(business_encryptId);
                                xwFarmDiscussinfo.setFarmEncryptid(farm_encryptId);
                                boolean disctemp = xwFarmDiscussinfoRepository.exists(Example.of(xwFarmDiscussinfo));
                                if(disctemp){
                                    //查询到有相关记录
                                    xwFarmDiscussinfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //农家乐美食信息
                                XwFarmFoodinfo xwFarmFoodinfo = new XwFarmFoodinfo();
                                xwFarmFoodinfo.setBusinessEncryptid(business_encryptId);
                                xwFarmFoodinfo.setFarmEncryptid(farm_encryptId);
                                boolean foodtemp = xwFarmFoodinfoRepository.exists(Example.of(xwFarmFoodinfo));
                                if(foodtemp){
                                    //查询到有相关记录
                                    xwFarmFoodinfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //农家乐住宿信息
                                XwFarmRoominfo xwFarmRoominfo = new XwFarmRoominfo();
                                xwFarmRoominfo.setBusinessEncryptid(business_encryptId);
                                xwFarmRoominfo.setFarmEncryptid(farm_encryptId);
                                boolean roomtemp = xwFarmRoominfoRepository.exists(Example.of(xwFarmRoominfo));
                                if(roomtemp){
                                    //查询到有相关记录
                                    xwFarmRoominfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //农家店铺基本信息
                                XwFarmBasicinfo xwFarmBasicinfo = new XwFarmBasicinfo();
                                xwFarmBasicinfo.setBusinessEncryptid(business_encryptId);
                                xwFarmBasicinfo.setFarmEncryptid(farm_encryptId);
                                boolean farmbastmep = xwFarmBasicinfoRepository.exists(Example.of(xwFarmBasicinfo));
                                if(farmbastmep){
                                    //查询到有相关记录
                                    xwFarmBasicinfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //删除匹配对应商户类型的记录
                                XwCustomShop xwCustomShop = new XwCustomShop();
                                xwCustomShop.setShopEncryptid(farm_encryptId);
                                boolean shoptemp = xwCustomShopRepository.exists(Example.of(xwCustomShop));
                                if(shoptemp){
                                    xwCustomShopRepository.deleteByShopEncryptid(farm_encryptId);
                                }

                                //用户基本信息
                                XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(business_encryptId);
                                if(userinfo != null){
                                    userinfo.setUserRole("0");
                                    xwUserinfoRepository.save(userinfo);
                                }
                                xwBusinessInfoRepository.deleteByBusinessEncryptid(business_encryptId);

                            } else if (!"0".equals(sec_encryptId) && !"".equals(sec_encryptId)) {
                                //删除景区的商家信息

                                //景区收藏信息
                                XwSceincCollectinfo xwSceincCollectinfo = new XwSceincCollectinfo();
                                xwSceincCollectinfo.setBusinessEncryptid(business_encryptId);
                                xwSceincCollectinfo.setScenictypeEncryptid(sec_encryptId);
                                boolean sceColltemp = xwSceincCollectinfoReository.exists(Example.of(xwSceincCollectinfo));
                                if(sceColltemp){
                                    //查询到有相关记录
                                    xwSceincCollectinfoReository.deleteByScenicEncryptid(sec_encryptId);
                                }

                                //景区图集信息
                                XwScenicAtlasinfo xwScenicAtlasinfo = new XwScenicAtlasinfo();
                                xwScenicAtlasinfo.setBusinessEncryptid(business_encryptId);
                                xwScenicAtlasinfo.setScenicEncryptid(sec_encryptId);
                                boolean sceAtlastemp = xwScenicAtlasinfoRepository.exists(Example.of(xwScenicAtlasinfo));
                                if(sceAtlastemp){
                                    //查询到有相关记录
                                    xwScenicAtlasinfoRepository.deleteByScenicEncryptid(sec_encryptId);
                                }

                                //景区评论信息
                                XwSceincDiscussinfo xwSceincDiscussinfo = new XwSceincDiscussinfo();
                                xwSceincDiscussinfo.setBusinessEncryptid(business_encryptId);
                                xwSceincDiscussinfo.setScenicEncryptid(sec_encryptId);
                                boolean scedistemp = xwSceincDiscussinfoReopsitory.exists(Example.of(xwSceincDiscussinfo));
                                if(scedistemp){
                                    //查询到有相关记录
                                    xwSceincDiscussinfoReopsitory.deleteByScenicEncryptid(sec_encryptId);
                                }

                                //景区娱乐项目
                                XwSceincEntertainment xwSceincEntertainment = new XwSceincEntertainment();
                                xwSceincEntertainment.setBusinessEncryptid(business_encryptId);
                                xwSceincEntertainment.setScenicEncryptid(sec_encryptId);
                                boolean sceentertemp = xwSceincEntertainmentRepository.exists(Example.of(xwSceincEntertainment));
                                if(sceentertemp){
                                    //查询到有相关记录
                                    xwSceincEntertainmentRepository.deleteByScenicEncryptid(sec_encryptId);
                                }

                                //景区基本信息
                                XwScenicBasicinfo xwScenicBasicinfo = new XwScenicBasicinfo();
                                xwScenicBasicinfo.setBusinessEncryptid(business_encryptId);
                                xwScenicBasicinfo.setScenicEncryptid(sec_encryptId);
                                boolean scebastemp = xwScenicBasicinfoRepository.exists(Example.of(xwScenicBasicinfo));
                                if(scebastemp){
                                    //查询到有相关记录
                                    xwScenicBasicinfoRepository.deleteByScenicEncryptid(sec_encryptId);
                                }

                                //删除匹配对应商户类型的记录
                                XwCustomShop xwCustomShop = new XwCustomShop();
                                xwCustomShop.setShopEncryptid(sec_encryptId);
                                boolean shoptemp = xwCustomShopRepository.exists(Example.of(xwCustomShop));
                                if(shoptemp){
                                    xwCustomShopRepository.deleteByShopEncryptid(sec_encryptId);
                                }

                                //用户基本信息
                                XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(business_encryptId);
                                if(userinfo != null){
                                    userinfo.setUserRole("0");
                                    xwUserinfoRepository.save(userinfo);
                                }
                                xwBusinessInfoRepository.deleteByBusinessEncryptid(business_encryptId);
                            }

                            result.put("status", 0);
                            result.put("msg", "ok");

                        } else {
                            //不存在
                            result.put("status", 500);
                            result.put("msg", "该商家不存在！");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    result.put("status", 500);
                    result.put("msg", e);
                }

            } else {
                result.put("status", 500);
                result.put("msg", "business_encryptId不能为空！");
            }
        }else {
            result.put("status",40001);
            result.put("msg","uid不能为空，请先登录后再操作！");
        }

        System.out.println("delbusinessinfo：" + result.toString());
        return result;
    }


    /**
     * 单个——获取单个用户信息
     * @param user_encryptId
     * @param request
     * @return
     */
    @Override
    public JSONObject getUserOne(String user_encryptId, HttpServletRequest request) {
        JSONObject result = new JSONObject();

        result = dal_xwUserinfo.getUserOne(user_encryptId,jdbcTemplate);

        System.out.println("getUserOne:"+result.toString());
        return result;
    }

    /**
     *  用户——修改兴趣爱好
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject modifyUserRemarks(String user_encryptId, String themeRemarks, String playRemarks,
                                        HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request,"uid").toString();
        if(!"".equals(uid_encryptid) && !"".equals(uid)){
            if(!"".equals(user_encryptId)){

                XwUserinfo xwUserinfo = new XwUserinfo();
                xwUserinfo.setUserEncryptid(user_encryptId);
                boolean temp = xwUserinfoRepository.exists(Example.of(xwUserinfo));
                if(temp){
                    try {
                        XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(user_encryptId);
                        userinfo.setUserHobbyZt(themeRemarks);
                        userinfo.setUserHobbyYw(playRemarks);
                        userinfo.setUserUpdatetime(new Date());
                        xwUserinfoRepository.save(userinfo);
                        result.put("status",0);
                        result.put("msg","ok");

                    }catch (Exception e){
                        e.printStackTrace();
                        result.put("status",40002);
                        result.put("msg",e);
                    }

                }else {
                    result.put("status",40002);
                    result.put("msg","该用户不存在！");
                }

            }else {
                result.put("status",40002);
                result.put("msg","user_encryptId不能为空！");
            }
        }else {
            result.put("status",40001);
            result.put("msg","uid不能为空,请先登录！");
        }
        System.out.println("modifyUserRemarks:"+result.toString());
        return result;
    }

    /**
     *  用户——修改用户基本信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject updateUserinfo(String user_encryptId, String updatefiled, String updateval,
                                     HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request,"uid").toString();
        if(!"".equals(uid_encryptid) && !"".equals(uid)){
            if(!"".equals(user_encryptId)){

                //验证用户信息是否存在
                XwUserinfo xwUserinfo = new XwUserinfo();
                xwUserinfo.setUserEncryptid(user_encryptId);
                boolean temp = xwUserinfoRepository.exists(Example.of(xwUserinfo));
                if(temp){
                    try {
                        if(updatefiled.equals("tel")){    //修改电话
                            //第一步 ：应查询该电话号码是否 已经存在（1、用户信息表）
                            List<XwUserinfo> user = xwUserinfoRepository.findByUserTel(updateval.trim());
                            if(user.size() == 0){
                                //第二步：不存在则修改成功，反之，提示：您要修改的电话已经有人注册，请重新添加电话
                                XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(user_encryptId);
                                userinfo.setUserTel(updateval);
                                userinfo.setUserUpdatetime(new Date());
                                xwUserinfoRepository.save(userinfo);

                                if("1".equals(userinfo.getUserRole())){
                                    //如果是商家,则同时更改商家信息表的电话号码
                                    XwBusinessInfo xwBusinessInfo = new XwBusinessInfo();
                                    xwBusinessInfo.setBusinessEncryptid(user_encryptId);
                                    boolean Teltemp = xwBusinessInfoRepository.exists(Example.of(xwBusinessInfo));
                                    if(Teltemp){
                                        XwBusinessInfo businessInfo = xwBusinessInfoRepository.findByBusinessEncryptid(user_encryptId);
                                        businessInfo.setBusinessTel(updateval.trim());
                                        xwBusinessInfoRepository.save(businessInfo);
                                    }
                                }

                                result.put("status",0);
                                result.put("msg","ok");
                            }else {
                                //已被人注册情况下
                                result.put("status",40002);
                                result.put("msg","联系电话已被他人注册！");
                            }

                        }else if(updatefiled.equals("sex")){ //修改性别
                            XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(user_encryptId);
                            userinfo.setUserSex(updateval);
                            userinfo.setUserUpdatetime(new Date());
                            xwUserinfoRepository.save(userinfo);
                            result.put("status",0);
                            result.put("msg","ok");

                        }else if(updatefiled.equals("email")){ //修改邮箱
                            XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(user_encryptId);
                            userinfo.setUserMail(updateval);
                            userinfo.setUserUpdatetime(new Date());
                            xwUserinfoRepository.save(userinfo);
                            result.put("status",0);
                            result.put("msg","ok");
                        }

                    }catch (Exception e){
                        e.printStackTrace();
                        result.put("status",40002);
                        result.put("msg",e);
                    }

                }else {
                    result.put("status",40002);
                    result.put("msg","该用户不存在！");
                }

            }else {
                result.put("status",40002);
                result.put("msg","user_encryptId不能为空！");
            }
        }else {
            result.put("status",40001);
            result.put("msg","uid不能为空,请先登录！");
        }
        System.out.println("updateUserinfo:"+result.toString());
        return result;
    }


    // 判断是农家乐商家，还是 景区商家
    @Override
    public JSONObject getuidBusinessType(String user_encryptid, String user_role, String userid,
                                      HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request,"uid").toString();
        if(!"".equals(uid_encryptid) && !"".equals(uid)){

            result = dal_xwUserinfo.getuidBusinessType(user_encryptid,user_role,userid,jdbcTemplate);

        }else {
            result.put("status",40001);
            result.put("msg","uid不能为空,请先登录！");
        }
        System.out.println("uidBusinessType:"+result.toString());
        return result;
    }

    //验证用户名是否存在
    @Override
    public JSONObject checkUsername(String username, HttpServletRequest request) {

        JSONObject result = dal_xwUserinfo.checkUsername(username,jdbcTemplate);
        System.out.println("checkUsername:"+result.toString());
        return result;
    }

    //验证电话号码是否存在
    @Override
    public JSONObject checkUsertel(String tel, HttpServletRequest request) {
        JSONObject result = dal_xwUserinfo.checkUsertel(tel,jdbcTemplate);
        System.out.println("checkUsertel:"+result.toString());
        return result;
    }


    public Dal_XwUserinfo getDal_xwUserinfo() {
        return dal_xwUserinfo;
    }

    public void setDal_xwUserinfo(Dal_XwUserinfo dal_xwUserinfo) {
        this.dal_xwUserinfo = dal_xwUserinfo;
    }


}
